package com.example.navigation.components

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.navigation.api.navigation.DeviceViewModel

/**
 * Created with IntelliJ IDEA.
 * @Author: Liao Run
 * @Date: 2024-06-09 21:02
 * @Description:
 **/
@Composable
fun DropDownDevices(
    modifier: Modifier,
    deviceViewModel: DeviceViewModel = hiltViewModel(),
    onSelected: (deviceId: String) -> Unit
) {
    DisposableEffect(key1 = Unit) {
        deviceViewModel.getDevices("8")
        onDispose { }
    }

    val state = deviceViewModel.getRes.collectAsState()
    deviceViewModel.timeout.collectAsState().value.let {
        if (it) {
            Log.i("tag", "DropDownDevices: 超时")
        }
    }
    var expanded by remember { mutableStateOf(false) }
    var deviceName by remember { mutableStateOf("") }

    Column {
        TextField(
            value = deviceName, onValueChange = {},
            enabled = false,
            modifier = Modifier
                .clickable {
                    expanded = true
                }.width(140.dp),
            placeholder = {
                Text(text = "点击选择设备")
            }
        )

        DropdownMenu(modifier = modifier, expanded = expanded, onDismissRequest = {
            expanded = false
        }) {

            state.value.data?.map {
                DropdownMenuItem(text = {
                    Text(text = it.car_name)
                }, onClick = {
                    // emit 给父组件切换选择了设备
                    deviceName = it.car_name
                    expanded = false
                    onSelected(it.car_bq)
                })
            }

        }
    }
}